package example.fast;

import java.io.File;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.Set;

public class MyClassloader extends ClassLoader {
    private Set<String> loadedClassSet =new HashSet<>();
    public MyClassloader(ClassLoader parent) {
        super(parent);
    }
    public boolean isLoad(String name){
        return loadedClassSet.contains(name);
    }
    public Class<?> defineClass(String name, String beanClass, String methodName, String desc) {
        try {
            loadedClassSet.add(name);
            byte[] bytes = MethodFactory.genClassBytes(beanClass, methodName, desc);
            // 把内存里的类字节码写入磁盘，方便分析
            File file = new File("dump/" + name.replaceAll("\\.", "_") + ".class");
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            Files.write(file.toPath(), bytes);
            return defineClass(name, bytes, 0, bytes.length);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
